/**
 * Created by scutterry on 16/3/30.
 * v1.1
 * modified 2017-03-05
 */
(function($){
    function f(){

    }

    window.MyNet = f;

    var list = [];
    var isBusy = false;
    var currentObj;

    f.loadingView = undefined;

    f.addLoading = function(){
        if(f.loadingView){
            $("body").append(f.loadingView);
        }else{
            console.log("loadingView is NOT initialized");
        }
    };

    f.removeLoading = function(){
        if(f.loadingView){
            f.loadingView.remove();
        }
    };

    

    f.post = function(url, data, callback, thisArg){
        if(typeof data === "object"){
            data = JSON.stringify(data);
        }
        var obj = {};
        obj.url = url;
        obj.data = data;
        obj.method = "post";
        obj.dataType = "json";
        obj.success = function(res){
            f.removeLoading();
            if(callback){
                callback.call(thisArg, res);
            }

            if(list.length > 0){
                f.ajax(list.pop());
            }else{
                isBusy = false;
            }
        };
        obj.error = f.error;
        if(isBusy){
            list.unshift(obj);
            console.log("post list");
            return;
        }


        isBusy = true;
        f.ajax(obj);
    };

    f.get = function(url, callback, thisArg){
        var obj = {};
        obj.url = url;
        obj.method = "get";
        obj.dataType = "json";
        obj.success = function(res){
            f.removeLoading();
            if(callback){
                callback.call(thisArg, res);
            }

            if(list.length > 0){
                f.ajax(list.pop());
            }else{
                isBusy = false;
            }
        };
        obj.error = f.error;
        if(isBusy){
            list.unshift(obj);
            console.log("get list");
            return;
        }

        isBusy = true;
        f.ajax(obj);
    };


    f.ajax = function(data){
        currentObj = data;
        f.addLoading();
        $.ajax(data);
    };

    f.error = function(){
        f.removeLoading();
        if(isNaN(currentObj.tryTime)){
            currentObj.tryTime = 1;
            f.ajax(currentObj);
        }else if(currentObj.tryTime < 3){
            currentObj.tryTime++;
            f.ajax(currentObj);
        }else{
            var len = list.length;
            for(var i = len - 1; i >= 0; i--){
                if(currentObj.url === list[i].url){
                    list.splice(i, 1);
                    break;
                }
            }
            alert("网络不稳定" + currentObj.url);
            if(list.length > 0){
                f.ajax(list.pop());
            }else{
                currentObj = null;
                isBusy = false;
            }
        }
    };

    return f;


})(jQuery);
